<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\facade\Builder;
use think\facade\View;
use think\response\Json;
//该文件为自动生成，请按需修改
class Level extends Base
{
    //所有定义变量均为演示，请根据实际需求更改

    //主键，默认为id
    protected string $pk = 'id';

    //主模型
    protected string $model = '\app\common\model\Level';

    //关联模型
    protected array $hasOne = [];

    //附加字段或者虚拟字段
    protected array $append = [];

    //数据排序，支持多个
    protected array $sort = ['id' => 'desc'];

    public function index(): string
    {
        //构建表格数据
        return Builder::Table()
            ->addColumn(['type' => 'checkbox', 'title' => '全选', 'fixed' => 'left'])
            ->addColumn(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addColumn(['field' => 'title', 'title' => '标题', 'modify' => '2,input'])
            ->addColumn(['field' => 'icon', 'title' => '图片', 'modify' => '2,img,1','templet' => '#iconTpl'])
            ->addColumn(['field' => 'money', 'title' => '升级条件（消费金额）', 'modify' => '2,number'])
            ->addColumn(['field' => 'discount', 'title' => '折扣', 'modify' => '2,ratio', 'templet' => '<div>{{(d.discount*100).toFixed(2)}}%</div>'])
            ->addColumn(['fixed' => 'right', 'title' => '操作', 'align' => 'center', 'toolbar' => '#barDemo', 'width' => 200])
            ->addRightButtons(['edit' => ['size' => '1000,1000']])
            ->addTopButtons(['add' => ['size' => '1000,1000']])
            ->addSearch([
                ['title', '等级标题搜索', 'input', '', '', '', 'like']
            ])
            ->fetch();
    }

    public function save($param = [], $model = false): Json
    {
        $param = $this->request->post();
        if ($param['discount'] > 100) {
            return json(['code' => -1, 'msg' => '折扣不能大于100%']);
        }
        if ($param['money'] < 0) {
            return json(['code' => -1, 'msg' => '消费金额不能小于0']);
        }
        if ($param['discount'] < 0) {
            return json(['code' => -1, 'msg' => '折扣不能小于0']);
        }
        $param['discount'] = $param['discount'] / 100;
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }
}
